package com.youth.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.youth.entity.vo.CommodityVO;
import com.youth.mapper.ICommodityMaper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @ClassName RMQConsumer
 * @Description: TODO
 * @Author yjwu
 * @Date 2020/1/17 10:35
 **/

//@RabbitListener(
//        bindings = @QueueBinding(
//                value = @Queue(value = "boot.queue1", durable = "true"),
//                exchange = @Exchange(value = "BOOT-EXCHANGE-1", type = "topic", durable = "true", ignoreDeclarationExceptions = "true"),
//                key = "boot.*"
//        )
//)
@Component
@Slf4j
public class SeckillRMQConsumer {
    @Autowired
    private ICommodityMaper commodityMaper;
    @Autowired
    @Qualifier(value = "objRedisTemplate")
    private RedisTemplate redisTemplate;


    @RabbitListener(
            queues = {"${seckillRMQQueueName}"})
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws IOException {
        // 限流处理：消息体大小不限制，每次限制消费一条，只作用于该Consumer层，不作用于Channel
//        channel.basicQos(0, 1, false);//限制于消费级别
        String s = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("SeckillRMQConsumer receive msg:{},deliveryTag：{}", s, deliveryTag);
        try {
            if (StringUtils.isEmpty(s) || !redisTemplate.hasKey(s)) {
                log.info("receive error msg:{}", s);
            } else {
                Object o = redisTemplate.opsForValue().get(s);
                String s1 = JSONObject.toJSONString(o);
                CommodityVO commodityVO = JSONObject.toJavaObject(JSON.parseObject(s1), CommodityVO.class);
                commodityMaper.decreaseStockNumber(s, commodityVO.getStorageNumber(), commodityVO.getSoldNumber(), new Date());
            }
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("e.getmessage:{}", e.getMessage());
            channel.basicReject(deliveryTag, false);
        }
    }
}
